#include "matscene.h"
#include "matitem.h"

MatScene::MatScene(const Mat &mat, const QRectF &sceneRect, QObject *parent)
    : QGraphicsScene(sceneRect, parent),
      m_mat(mat),
      m_pen(Qt::lightGray, 1),
      m_brush(Qt::black),
      m_gridItem(Q_NULLPTR),
      m_itemGrid()
{
    setupUi(mat, sceneRect);
}

MatScene::~MatScene()
{
}

MatItem *MatScene::itemAt(qint32 m, qint32 n)
{
    return m_itemGrid[m][n];
}

void MatScene::setItemsColor(qint32 type, const QColor &color)
{
    for (auto &itemsRow: m_itemGrid) {
        for (MatItem *item : itemsRow) {
            item->setColor(type, color);
        }
    }
}

void MatScene::setupUi(const Mat &mat, const QRectF &sceneRect)
{
    addMesh(mat, sceneRect);
    addGrid(mat, sceneRect);
}

void MatScene::addMesh(const Mat &mat, const QRectF &sceneRect)
{
    qint32 m = mat.m();
    qint32 n = mat.n();
    qreal size = mat.size();

    qreal left = sceneRect.left();
    qreal top = sceneRect.top();
    qreal right = sceneRect.right();
    qreal bottom = sceneRect.bottom();

    for (qint32 row = 0; row <= m; ++row) {
        addLine(left, row*size, right, row*size, m_pen);
    }
    for (qint32 col = 0; col <= n; ++col) {
        addLine(col*size, top, col*size, bottom, m_pen);
    }
}

void MatScene::addGrid(const Mat &mat, const QRectF &sceneRect)
{
    if (m_gridItem) removeItem(m_gridItem);
    m_gridItem = addRect(sceneRect, Qt::NoPen, Qt::NoBrush);

    qint32 m = mat.m();
    qint32 n = mat.n();
    qreal size = mat.size();

    QSize itemSize(size, size);
    qreal left = sceneRect.left();
    qreal top = sceneRect.top();
    qreal x = left, y = top;

    m_itemGrid.resize(m);
    for (qint32 row = 0; row < m; ++row) {
        x = left;
        m_itemGrid[row].resize(n);
        for (qint32 col = 0; col < n; ++col) {
            MatItem *item = new MatItem(QRectF(QPointF(x, y), itemSize), m_gridItem);
            item->setData(MatItem::kDataPos, QPoint(col, row));
            m_itemGrid[row][col] = item;
            x += size;
        }
        y += size;
    }
}
